//
//  LGMedicineBallPhoneController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/8/28.
//  药球管理 -- 电话随访

#import "LGMedicineBallPhoneController.h"
//随访记录
#import "LGMedicineBallFollowUpRecorder.h"
//修改手机号
#import "LGChangePatientPhoneView.h"
#import <CallKit/CXCallObserver.h>
#import <CallKit/CXCall.h>

@interface LGMedicineBallPhoneController ()<CXCallObserverDelegate>
/**   */
@property (nonatomic , strong)UIView *tipView;
/**   */
@property (nonatomic , strong)UIImageView *doctorPic;
/**   */
@property (nonatomic , strong)UIImageView *patientPic;
/**   */
@property (nonatomic , strong)UILabel *doctorLabel;
/**   */
@property (nonatomic , strong)UILabel *patientLabel;
/**   */
@property (nonatomic , strong)UILabel *doctorPhone;
/**   */
@property (nonatomic , strong)UILabel *patientPhone;
/**   */
@property (nonatomic , strong)UIButton *doctorTip;
/**   */
@property (nonatomic , strong)UIButton *patientTip;
/**   */
@property (nonatomic , strong)UIView *bottomView;
/**   */
@property (nonatomic , strong)UIButton *phoneBtn;
/**   */
@property (nonatomic , strong)UIButton *addButton;
/**   */
@property (nonatomic , strong)UIButton *phoneBtn2;
/**   */
@property (nonatomic , strong)UIButton *cancelBtn;
/**   */
@property (nonatomic , strong)CXCallObserver *observer;

@end

@implementation LGMedicineBallPhoneController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.levelid = (_levelid && ![_levelid isEmptyString])?_levelid:@"";
    [self createSubView];
    [self requestData];
    if (!self.observer) {
        self.observer = [[CXCallObserver alloc] init];
        [self.observer setDelegate:self queue:dispatch_get_main_queue()];
    }
}

-(void)requestData{
    NSString *action = @"/doctor/patient.dcb.patient/getPhoneInfo";
    NSDictionary *parama = @{@"plan_id":self.planid,@"patient_id":self.patientid,@"level_id":self.levelid};
    if ([self.type isEqualToString:@"appoint"]) {
        //电话咨询
        self.navigationView.title = @"电话咨询";
        action = @"/doctor/visit.Visit/getAppointmentPhoneInfo";
        parama = @{@"appointment_id":self.planid};
    }
    [RequestUtil withPOST:action parameters:parama withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            NSDictionary *doctorDic = returnData[@"doctor"];
            NSDictionary *patientDic = returnData[@"patient"];
            self.doctorLabel.text = LGNSString(doctorDic[@"realname"]);
            [self.doctorPic sd_setImageWithURL:[NSURL URLWithString:LGNSString(doctorDic[@"avatar_url"])]];
            self.doctorPhone.text = [LGNSString(doctorDic[@"mobile"]) stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
            [self.patientPic sd_setImageWithURL:[NSURL URLWithString:LGNSString(patientDic[@"avatar_url"])]];
            self.patientLabel.text = LGNSString(patientDic[@"realname"]);
            self.patientPhone.text = LGNSString(patientDic[@"mobile"]);
            self.patientid = LGNSString(patientDic[@"patient_id"]);
        }
    } error:^(NSError *error) {
        
    }];
}

//修改患者手机号
-(void)changePatientPhone{
    LGChangePatientPhoneView *phoneView = [[LGChangePatientPhoneView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    [[UIApplication sharedApplication].keyWindow addSubview:phoneView];
    __weak typeof(self) weakSelf = self;
    phoneView.changePatientPhone = ^(NSString * _Nonnull phone) {
        [RequestUtil withPOST:@"/doctor/patient.dcb.patient/savePatientPhone" parameters:@{@"patient_id":self.patientid,@"mobile":phone,@"level_id":self.levelid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [TooltipView showMessage:@"保存成功" offset:0];
                [weakSelf requestData];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:@"保存失败，请重试" offset:0];
        }];
    };
}

//拨打电话
-(void)makePhoneCallAction{
    NSString *action = @"/doctor/patient.dcb.patient/phoneCall";
    NSDictionary *parama = @{@"plan_id":self.planid,@"patient_id":self.patientid,@"level_id":self.levelid};
    if ([self.type isEqualToString:@"appoint"]) {
        //电话咨询
        action = @"/doctor/visit.Visit/phoneCall";
        parama = @{@"appointment_id":self.planid};
    }
    [RequestUtil withPOST:action parameters:parama withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            NSString *callNumber = [NSString stringWithFormat:@"telprompt://%@",returnData[@"relation_number"]];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callNumber] options:@{} completionHandler:^(BOOL success) {
                
            }];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:@"拨打电话失败，请重试" offset:0];
    }];
}

//添加随访总结
-(void)addFollowRecordAction{
    LGMedicineBallFollowUpRecorder *controller = [[LGMedicineBallFollowUpRecorder alloc]init];
    controller.planid = self.planid;
    controller.patientid = self.patientid;
    [self.navigationController pushViewController:controller animated:YES];
}

//拨打电话状态
-(void)callObserver:(CXCallObserver *)callObserver callChanged:(CXCall *)call{
    if(call.outgoing && call.hasEnded){
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.phoneBtn.hidden = YES;
            weakSelf.phoneBtn2.hidden = NO;
            weakSelf.addButton.hidden = NO;
        });
        return;
    }
}

//结束电话随访
-(void)cancelPhoneAction{
    [RequestUtil withPOST:@"/doctor/patient.dcb.patient/phoneClearBind" parameters:@{@"patient_id":self.patientid,@"level_id":self.levelid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [TooltipView showMessage:@"已结束电话" offset:0];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:@"结束失败，请重试" offset:0];
    }];
}

-(void)dealloc{
    if(self.observer){
        [self.observer setDelegate:nil queue: dispatch_get_main_queue()];
        self.observer = nil;
    }
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.navigationView.title = @"电话随访";
    self.fd_prefersNavigationBarHidden = YES;
    [self.view addSubview:self.navigationView];
    [self createTipView];
    [self.view addSubview:self.doctorPic];
    [self.view addSubview:self.doctorLabel];
    [self.view addSubview:self.doctorPhone];
    [self.view addSubview:self.doctorTip];
    [self.view addSubview:self.patientPic];
    [self.view addSubview:self.patientLabel];
    [self.view addSubview:self.patientPhone];
    [self.view addSubview:self.patientTip];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.cancelBtn];
    [self.bottomView addSubview:self.phoneBtn];
    [self.bottomView addSubview:self.addButton];
    [self.bottomView addSubview:self.phoneBtn2];
}

-(UIImageView *)doctorPic{
    if(!_doctorPic){
        _doctorPic = [[UIImageView alloc]initWithFrame:CGRectMake(viewPix(42), viewPix(87)+topBarHeight, viewPix(100), viewPix(100))];
        _doctorPic.cornerRidus = viewPix(50);
    }
    return _doctorPic;
}

-(UILabel *)doctorLabel{
    if(!_doctorLabel){
        _doctorLabel = [UILabel lableWithText:@"" colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentCenter lines:1];
        _doctorLabel.frame = CGRectMake(viewPix(20), kMaxY(self.doctorPic.frame)+viewPix(12), Screen_W/2.0-viewPix(40), viewPix(22));
    }
    return _doctorLabel;
}

-(UILabel *)doctorPhone{
    if(!_doctorPhone){
        _doctorPhone = [UILabel lableWithText:@"" colorString:@"#333333" textFont:LGFontWeight(20, UIFontWeightMedium) textAlignment:NSTextAlignmentCenter lines:1];
        _doctorPhone.frame = CGRectMake(viewPix(20), kMaxY(self.doctorLabel.frame)+viewPix(10), Screen_W/2.0-viewPix(40), viewPix(28));
    }
    return _doctorPhone;
}

-(UIButton *)doctorTip{
    if(!_doctorTip){
        _doctorTip = [UIButton buttonWithTitle:@"将使用该号码加密呼出" titleFont:LGFontWeight(12, UIFontWeightMedium) textColor:@"#999999" imageName:@""];
        _doctorTip.frame = CGRectMake(viewPix(20), kMaxY(self.doctorPhone.frame)+viewPix(2), Screen_W/2.0-viewPix(40), viewPix(24));
        _doctorTip.userInteractionEnabled = NO;
    }
    return _doctorTip;
}

-(UIImageView *)patientPic{
    if(!_patientPic){
        _patientPic = [[UIImageView alloc]initWithFrame:CGRectMake(Screen_W-viewPix(142), viewPix(87)+topBarHeight, viewPix(100), viewPix(100))];
        _patientPic.cornerRidus = viewPix(50);
    }
    return _patientPic;
}

-(UILabel *)patientLabel{
    if(!_patientLabel){
        _patientLabel = [UILabel lableWithText:@"" colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentCenter lines:1];
        _patientLabel.frame = CGRectMake(viewPix(20)+Screen_W/2.0, kMaxY(self.patientPic.frame)+viewPix(12), Screen_W/2.0-viewPix(40), viewPix(22));
    }
    return _patientLabel;
}

-(UILabel *)patientPhone{
    if(!_patientPhone){
        _patientPhone = [UILabel lableWithText:@"" colorString:@"#333333" textFont:LGFontWeight(20, UIFontWeightMedium) textAlignment:NSTextAlignmentCenter lines:1];
        _patientPhone.frame = CGRectMake(viewPix(20)+Screen_W/2.0, kMaxY(self.patientLabel.frame)+viewPix(10), Screen_W/2.0-viewPix(40), viewPix(28));
    }
    return _patientPhone;
}

-(UIButton *)patientTip{
    if(!_patientTip){
        _patientTip = [UIButton buttonWithTitle:@"不是患者号码？请修改" titleFont:LGFontWeight(12, UIFontWeightMedium) textColor:@"#2E8FFF" imageName:@"blueTip12"];
        _patientTip.frame = CGRectMake(viewPix(20)+Screen_W/2.0, kMaxY(self.patientPhone.frame)+viewPix(2), Screen_W/2.0-viewPix(40), viewPix(24));
        [_patientTip setButtonInsetsStyle:LGButtonInsetsStyleRight marginSpace:5];
        [_patientTip addTarget:self action:@selector(changePatientPhone) forControlEvents:UIControlEventTouchUpInside];
    }
    return _patientTip;
}


-(UIView *)bottomView{
    if(!_bottomView){
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, Screen_H-viewPix(72)-bottomSafeBarHeight/4.0, Screen_W, viewPix(72))];
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

-(UIButton *)phoneBtn{
    if(!_phoneBtn){
        _phoneBtn = [UIButton buttonWithTitle:@"开始免费通话" topMargin:viewPix(10)];
        [_phoneBtn addTarget:self action:@selector(makePhoneCallAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _phoneBtn;
}

-(UIButton *)addButton{
    if(!_addButton){
        _addButton = [UIButton buttonWithTitle:@"添加随访总结" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#429BFF" imageName:@""];
        _addButton.frame = CGRectMake(viewPix(48), viewPix(10), viewPix(128), viewPix(46));
        _addButton.layer.borderColor = [UIColor colorWithString:@"#429BFF"].CGColor;
        _addButton.layer.borderWidth = 1;
        _addButton.cornerRidus = 10;
        _addButton.hidden = YES;
        [_addButton addTarget:self action:@selector(addFollowRecordAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addButton;
}


-(UIButton *)phoneBtn2{
    if(!_phoneBtn2){
        _phoneBtn2 = [UIButton buttonWithTitle:@"再次呼叫" topMargin:viewPix(8)];
        _phoneBtn2.frame = CGRectMake(Screen_W-viewPix(176), viewPix(10), viewPix(128), viewPix(46));
        _phoneBtn2.hidden = YES;
        [_phoneBtn2 addTarget:self action:@selector(makePhoneCallAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _phoneBtn2;
}

-(UIButton *)cancelBtn{
    if(!_cancelBtn){
        _cancelBtn = [UIButton buttonWithTitle:@"结束电话" titleFont:LGFontWeight(13, UIFontWeightMedium) textColor:@"#999999" imageName:@"电话随访-结束"];
        _cancelBtn.frame = CGRectMake((Screen_W-viewPix(80))/2.0, kMinY(self.bottomView.frame)-viewPix(180), viewPix(80), viewPix(110));
        [_cancelBtn setButtonInsetsStyle:LGButtonInsetsStyleTop marginSpace:15];
        [_cancelBtn addTarget:self action:@selector(cancelPhoneAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

-(void)createTipView{
    UIView *tipView = [[UIView alloc]initWithFrame:CGRectMake(0, topBarHeight, Screen_W, viewPix(57))];
    tipView.backgroundColor = [UIColor colorWithString:@"#FEF7EE"];
    [self.view addSubview:tipView];
    UIImageView *iconView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"电话随访-惊叹号"]];
    iconView.frame = CGRectMake(viewPix(12), viewPix(10), viewPix(12), viewPix(12));
    [tipView addSubview:iconView];
    UILabel *contentLabel = [UILabel lableWithText:[NSString stringWithFormat:@"请确保手机默认拨号SIM卡和%@app账号一致，否则无法接通",AppTitle] colorString:@"#333333" textFont:LGFont(15) textAlignment:NSTextAlignmentLeft lines:2];
    contentLabel.frame = CGRectMake(viewPix(28), viewPix(6), Screen_W-viewPix(35), viewPix(45));
    [contentLabel lineSpacing:5];
    [tipView addSubview:contentLabel];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
